package com.yqg.protection.controller;


import com.yqg.protection.common.Result;
import com.yqg.protection.common.interceptor.SysLog;
import com.yqg.protection.entity.SimInputStore;
import com.yqg.protection.mapper.OrganizationMapper;
import com.yqg.protection.mapper.SimInputStoreMapper;
import com.yqg.protection.service.*;
import com.yqg.protection.utils.Constants;
import com.yqg.protection.utils.OrganUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * SimInputStoreController 前端控制器
 *
 * @author zxf
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/sim-input-store")
public class SimInputStoreController {

    @Resource
    private ISimInputStoreService simInputStoreService;

    @Resource
    private SimInputStoreMapper simInputStoreMapper;

    @Autowired
    private IEquipmentInputStoreService equipmentInputStoreService;

    @Autowired
    private IVideoDeviceService videoDeviceService;

    @Autowired
    private IClientService clientService;

    @Autowired
    private OrganUtils organUtils;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private IAnnounceService announceService;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @SysLog("新增或者修改SIM卡")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody SimInputStore simInputStore) {
//        if (ObjectUtil.isEmpty(simInputStore.getId())) {
//            LambdaQueryWrapper<SimInputStore> simInputStoreQueryWrapper = new LambdaQueryWrapper<>();
//            simInputStoreQueryWrapper.eq(SimInputStore::getSimId, simInputStore.getSimId());
//            simInputStoreQueryWrapper.eq(SimInputStore::getIsDelete, 0);
//            SimInputStore simInputStore1 = simInputStoreService.getOne(simInputStoreQueryWrapper);
//            if (simInputStore1 != null) {
//                return Result.error(Constants.CODE_500, "该SIM卡已存在");
//            }
//            simInputStore.setInputTime(LocalDateTimeUtil.now());
//            simInputStore.setIsDelete(0);
//        } else {
//            SimInputStore simInputStore1 = simInputStoreService.getById(simInputStore.getId());
//            if (simInputStore1.getEquipmentInputStoreId() != null && simInputStore1.getEquipmentInputStoreId() != simInputStore.getEquipmentInputStoreId()) {
//                if (simInputStore1.getDeviceBindingType() == 0) {
//                    EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(simInputStore1.getEquipmentInputStoreId());
//                    equipmentInputStore.setDeviceBindingSim(0);
//                    equipmentInputStore.setSimInputStoreId(null);
//                    equipmentInputStoreService.updateById(equipmentInputStore);
//                } else {
//                    VideoDevice videoDevice = videoDeviceService.getById(simInputStore1.getEquipmentInputStoreId());
//                    videoDevice.setDeviceBindingSim(0);
//                    videoDevice.setSimInputStoreId(null);
//                    videoDeviceService.updateById(videoDevice);
//                }
//            }
//        }
//        if (simInputStore.getEquipmentInputStoreId() != null) {
//            simInputStore.setDeviceBindingEquipment(1);
//        } else {
//            simInputStore.setDeviceBindingEquipment(0);
//        }
//        simInputStoreService.saveOrUpdate(simInputStore);
//        if (simInputStore.getDeviceBindingEquipment() == 1) {
//            if (simInputStore.getDeviceBindingType() == 0) {
//                EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(simInputStore.getEquipmentInputStoreId());
//                equipmentInputStore.setDeviceBindingSim(1);
//                equipmentInputStore.setSimInputStoreId(simInputStore.getId());
//                equipmentInputStoreService.updateById(equipmentInputStore);
//            } else {
//                VideoDevice videoDevice = videoDeviceService.getById(simInputStore.getEquipmentInputStoreId());
//                videoDevice.setDeviceBindingSim(1);
//                videoDevice.setSimInputStoreId(simInputStore.getId());
//                videoDeviceService.updateById(videoDevice);
//            }
//        }
//        if (simInputStore.getTime() != null && LocalDateTime.now().plusMonths(1L).isAfter(simInputStore.getTime())) {
//            LambdaQueryWrapper<Announce> announceQueryWrapper = new LambdaQueryWrapper<>();
//            announceQueryWrapper.eq(Announce::getType, "1");
//            announceQueryWrapper.eq(Announce::getEquipOrSimId, simInputStore.getId());
//            announceService.remove(announceQueryWrapper);
//        }
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("delete/{id}")
    @SysLog("删除SIM卡")
    public Result delete(@PathVariable Integer id) {
        SimInputStore simInputStore = simInputStoreService.getById(id);
        if (!simInputStore.getState().equals("2")) {
            return Result.error(Constants.CODE_500, "SIM卡未注销，无法删除");
        }
        simInputStore.setIsDelete(1);
        return Result.success(simInputStoreService.saveOrUpdate(simInputStore));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    @ApiOperation("查询未绑定设备的SIM卡号")
    public Result findAll(@RequestParam Integer pageNum,
                          @RequestParam Integer pageSize,
                          String SIMId,
                          Integer level,
                          Long organizationId,
                          String isAllClient,
                          @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        List<SimInputStore> simInputStoreList = simInputStoreMapper.findPage(pageNum, pageSize, SIMId, "1", level, organizationId, 0, isAllClient, clientIds);
        Long count = simInputStoreMapper.findPageCount(SIMId, "1", level, organizationId, 0, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", simInputStoreList);
        map.put("total", count);
        return Result.success(map);
    }

    @GetMapping("/appAll")
    @ApiOperation("查询未绑定设备的SIM卡号")
    public Result appAll(String SIMId,
                          Integer level,
                          Long organizationId,
                          String isAllClient,
                          @RequestParam List<Long> clientIds) {
        List<SimInputStore> simInputStoreList = simInputStoreMapper.findAppAll(SIMId, "1", level, organizationId, 0, isAllClient, clientIds);
        return Result.success(simInputStoreList);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(simInputStoreService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           Integer level,
                           String SIMId,
                           Long organizationId,
                           Integer deviceBindingEquipment,
                           String state,
                           String isAllClient,
                           @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        List<SimInputStore> simInputStoreList = simInputStoreMapper.findPage(pageNum, pageSize, SIMId, state, level, organizationId, deviceBindingEquipment, isAllClient, clientIds);
        Long count = simInputStoreMapper.findPageCount(SIMId, state, level, organizationId, deviceBindingEquipment, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", simInputStoreList);
        map.put("total", count);
        return Result.success(map);
    }

    @PostMapping("/updateState")
    @ApiOperation("注销SIM卡")
    @SysLog("注销SIM卡")
    public Result updateState(@RequestBody SimInputStore simInpsutStore) {
        if (simInpsutStore.getDeviceBindingEquipment() == 1) {
            return Result.error(Constants.CODE_500, "SIM卡已绑定设备，无法注销");
        }
        simInpsutStore.setOrganization(null);
        simInpsutStore.setState("2");
        simInpsutStore.setDataPackage(null);
        simInpsutStore.setTime(null);
        return Result.success(simInputStoreService.saveOrUpdate(simInpsutStore));
    }

    @PostMapping("/updateDeviceBindingSim")
    @ApiOperation("修改设备与SIM卡的绑定状态")
    @SysLog("修改设备与SIM卡的绑定状态")
    @Transactional(rollbackFor = Exception.class)
    public Result updateDeviceBindingSim(@RequestBody SimInputStore simInputStore) {
//        if (simInputStore.getEquipmentInputStoreId() != null) {
//            simInputStore.setDeviceBindingEquipment(1);
//        } else {
//            simInputStore.setDeviceBindingEquipment(0);
//            simInputStore.setDeviceBindingType(null);
//        }
//        SimInputStore simInputStore1 = simInputStoreService.getById(simInputStore.getId());
//        if (simInputStore1.getEquipmentInputStoreId() != null) {
//            if (simInputStore1.getDeviceBindingType() == 0) {
//                EquipmentInputStore equipmentInputStore1 = equipmentInputStoreService.getById(simInputStore1.getEquipmentInputStoreId());
////            if (equipmentInputStore1.getState().equals("1")) {
////                return Result.error(Constants.CODE_500, "设备在线，无法解绑");
////            } else {
////                equipmentInputStore1.setState("0");
//                equipmentInputStore1.setDeviceBindingSim(0);
//                equipmentInputStore1.setSimInputStoreId(null);
//                equipmentInputStoreService.updateById(equipmentInputStore1);
////            }
//            } else {
//                VideoDevice videoDevice = videoDeviceService.getById(simInputStore1.getEquipmentInputStoreId());
//                videoDevice.setDeviceBindingSim(0);
//                videoDevice.setSimInputStoreId(null);
//                videoDeviceService.updateById(videoDevice);
//            }
//        }
//        simInputStoreService.saveOrUpdate(simInputStore);
//        if (simInputStore.getEquipmentInputStoreId() != null) {
//            if (simInputStore.getDeviceBindingType() == 0) {
//                EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(simInputStore.getEquipmentInputStoreId());
//                equipmentInputStore.setDeviceBindingSim(simInputStore.getDeviceBindingEquipment());
//                equipmentInputStore.setSimInputStoreId(simInputStore.getId());
////            equipmentInputStore.setState("1");
//                equipmentInputStoreService.updateById(equipmentInputStore);
//            } else {
//                VideoDevice videoDevice = videoDeviceService.getById(simInputStore.getEquipmentInputStoreId());
//                videoDevice.setDeviceBindingSim(1);
//                videoDevice.setSimInputStoreId(simInputStore.getId());
//                videoDeviceService.updateById(videoDevice);
//            }
//        }
//        if (simInputStore.getTime() != null && LocalDateTime.now().plusMonths(1L).isAfter(simInputStore.getTime())) {
//            LambdaQueryWrapper<Announce> announceQueryWrapper = new LambdaQueryWrapper<>();
//            announceQueryWrapper.eq(Announce::getType, "1");
//            announceQueryWrapper.eq(Announce::getEquipOrSimId, simInputStore.getId());
//            announceService.remove(announceQueryWrapper);
//        }
        return Result.success();
    }

    @ApiOperation("导出数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       Integer level,
                       String SIMId,
                       Long organizationId,
                       Integer deviceBindingEquipment,
                       String state,
                       String isAllClient,
                       @RequestParam List<Long> clientIds) {
        simInputStoreService.export(response, SIMId, state, level, organizationId, deviceBindingEquipment, isAllClient, clientIds);
    }

    @ApiOperation("导入数据")
    @PostMapping("/importData")
    @SysLog("导入SIM卡")
    public void importData(MultipartFile file) {
        simInputStoreService.importData(file);
    }
}

